<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加分类区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 树形表格区域 -->
      <tree-table
        class="tree-table"
        :data="cateList"
        :columns="columns"
        border
        show-index
        index-text="#"
        :selection-type="false"
        :expand-type="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: green"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditCateDialog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button 
          type="danger" 
          icon="el-icon-delete" 
          size="mini"
          @click="deleteCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 底部分页器区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        :rules="CateFormRules"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProp"
            size="small"
            clearable
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClose"
    >
      <!-- 编辑分类表单区域 -->
      <el-form :model="editCateForm" ref="editCateFormRef" :rules="CateFormRules" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类列表数据
      cateList: [],
      // 商品分类的页码
      total: 0,
      // 树形表格的配置
      columns: [
        { label: "分类名称", prop: "cat_name" },
        { label: "是否有效", type: "template", template: "isok" },
        { label: "排序", type: "template", template: "order" },
        { label: "操作", type: "template", template: "opt" },
      ],
      // 添加分类对话框的展示
      addCateDialogVisible: false,
      // 添加分类表单数据源
      addCateForm: {
        // 分类父 id
        cat_pid: 0,
        //分类名称
        cat_name: "",
        //分类层级
        cat_level: 0,
      },
      //添加分类表单验证规则
      CateFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 级联数据源
      parentCateList: [],
      // 父级分类选中的 id 值
      selectedKeys: [],
      // 级联选择器的配置项
      cascaderProp: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true,
      },
      // 编辑分类对话框的显示
      editCateDialogVisible: false,
      // 编辑分类表单数据
      editCateForm: {}
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 请求商品列表数据
    async getCateList() {
      let { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("加载失败!");
      this.total = res.data.total;
      this.cateList = res.data.result;
    },

    // 监听pagesize
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCateList();
    },

    // 监听 pagenum
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },

    // 添加分类对话框的展示
    async showAddCateDialog() {
      // 对话框展示之前请求获取商品分类数据
      let { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品列表失败！");
      }
      this.parentCateList = res.data;
      this.addCateDialogVisible = true;
    },

    //  级联选择发送变化的时候触发
    parentCateChanged() {
      // 把 添加分类表单里的数据更改
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
        this.addCateForm.cat_level = this.selectedKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },

    // 对话框关闭清空表单 重置级联选择器
    addCateDialogClose() {
      // 重置输入框
      this.$refs.addCateFormRef.resetFields();
      // 重置级联选择器
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },

    // 点击按钮添加新的商品分类
    addCate() {
      // 表单预验证
      this.$refs.addCateFormRef.validate(async (vali) => {
        if (!vali) return;
        // 发请求添加分类
        let { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败！");
        }
        this.$message.success("添加分类成功！");
        this.getCateList();
        this.addCateDialogVisible = false;
      });
    },

    // 编辑分类对话框的展示
    async showEditCateDialog(cateId) {
      // 在对话框展示之前通过 cateId 请求数据
      let {data: res} = await this.$http.get(`categories/${cateId}`)
      if(res.meta.status !== 200) return this.$message.error('加载失败！')
      this.editCateForm = res.data
      // 对话框展示
      this.editCateDialogVisible = true;
    },

    // 编辑对话框关闭后重置表单
    editCateDialogClose() {
      this.$refs.editCateFormRef.resetFields()
    },

    // 发请求修改分类
    editCate() {
      // 表单的预雁阵
      this.$refs.editCateFormRef.validate(async vali => {
        if(!vali) return 
        let {data: res} = await this.$http.put(`categories/${this.editCateForm.cat_id}`,{cat_name: this.editCateForm.cat_name})
        if(res.meta.status !== 200) return this.$message.error('修改分类失败！')
        this.$message.success('修改分类名称成功！')
        this.getCateList()
        this.editCateDialogVisible = false;
      })
    },

    // 删除商品分类
    async deleteCate(cateId) {
      let confirm = await this.$confirm('此操作将永久删除该商品分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirm !== 'confirm') return this.$message.info('已取消了删除！')
        let {data: res} = await this.$http.delete(`categories/${cateId}`)
        if(res.meta.status !== 200) return this.$message.error('删除分类失败！')
        this.$message.success('删除分类成功！')
        this.getCateList()
    }
  },
};
</script>

<style lang="less" scoped>
.tree-table {
  margin: 15px 0;
}
.el-cascader {
  width: 100%;
}
</style>